package com.chen.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.reggie.common.R;
import com.chen.reggie.dto.DishDto;
import com.chen.reggie.pojo.Category;
import com.chen.reggie.pojo.Dish;
import com.chen.reggie.pojo.DishFlavor;
import com.chen.reggie.service.CategoryService;
import com.chen.reggie.service.DishFlavorService;
import com.chen.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName DishController
 * @Description 菜品管理
 * @Author hainc
 * @Date 2022/9/5 9:50
 * @Version 1.0
 **/
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    //新增菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
    dishService.saveWithFlavor(dishDto);
//        String key = "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
//        redisTemplate.delete(key);
    return R.success("新增菜品成功");

    }

    //修改菜品
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);

        //清理所有菜品的redis缓存数据
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        //清理对应分类的菜品redis缓存
//        String key = "dish_"+dishDto.getCategoryId()+"_"+dishDto.getStatus();
//        redisTemplate.delete(key);

        //清空缓存数据，使用切面类

        return R.success("修改菜品成功");
    }

    //删除菜品
    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids){
        if(ids==null){
            return R.error("菜品删除失败，id为空");
        }
        dishService.removeByIds(ids);
        dishFlavorService.removeByIds(ids);

        return R.success("菜品删除成功");
    }

    //菜品信息分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        Page<Dish> pageInfo = new Page<>(page,pageSize);
        //Page里面的records包含所有菜品的信息，disDto里面保存菜品名称，是根据records里面获取categoryId查询出名称，再保存
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,queryWrapper);//pageinfo的records里面只有categoryId，需要查询categoryName

        //把pageInfo里面所有的信息拷贝到dishDtoPage里面，然后在根据categoryId查询菜品名称存放到DishDto里面
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> dishDtoList = new ArrayList<>();
        for(Dish dish : records){
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dishDto.setCategoryName(category.getName());
            dishDtoList.add(dishDto);
        }

        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);

    }

    //根据id查询菜品已经口味进行回显数据
    @GetMapping("/{id}")
    public R<DishDto> getDishAndFlavor(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * @param [dish]
     * @return com.chen.reggie.common.R<java.util.List < com.chen.reggie.pojo.Dish>>
     * 根据分类id查询菜品集合
     * @date 2022/9/6
     **/
//    @GetMapping("/list")
//    public R<List<Dish>> listDish( Dish dish) {
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
//        queryWrapper.eq(Dish::getStatus,1);//起售状态
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//
//        List<Dish> list = dishService.list(queryWrapper);
//
//        return R.success(list);
//
//    }

    @GetMapping("/list")
    public R<List<DishDto>> listDish( Dish dish) {
        List<DishDto> dishDtoList = null;

        //构造key存储在redis
        String key  = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();//dish_3323234223_1

        //从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //判断dishDtoList是否空
        if(dishDtoList != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }

        //否则构成条件查询数据库

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);//起售状态
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);
        //用dishDto替代dish对象，数据拷贝
            dishDtoList = list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);//  拷贝菜品基本信息
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                dishDto.setCategoryName(category.getName());
            }
            //dto对象缺口味数据
            Long id = item.getId();//菜品id
            //根据菜品id查询对应口味集合
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
            //口味集合
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //查询到数据，并保存到redis,60分钟
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        return R.success(dishDtoList);

    }

}
